package com.res.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.res.entity.Department;
import com.res.entity.Teacher;
import com.res.repository.TeacherRepository;
import com.res.service.TeacherService;

@Service
public class TeacherServiceImpl implements TeacherService {
	@Autowired
	private TeacherRepository rep;

	@Override
	public Page<Teacher> getTeacherAll(Teacher t, Pageable pageable, Integer tid) {
		// TODO Auto-generated method stub
		return rep.findAll(get(t, tid), pageable);
	}

	public Specification<Teacher> get(Teacher t, Integer tid) {
		return new Specification<Teacher>() {

			@Override
			public Predicate toPredicate(Root<Teacher> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				// TODO Auto-generated method stub
				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if (!StringUtils.isEmpty(t.getTname())) {
					expressions.add(criteriaBuilder.like(root.get("tname"), "%" + t.getTname() + "%"));
				}
				if (tid != null && tid != 0) {
					expressions.add(criteriaBuilder.equal(root.get("department").get("tid"), tid));
				}
				return predicate;
			}
		};
	}

	@Override
	public String addTeacher(Teacher t, Integer tid) {
		// TODO Auto-generated method stub
		try {
			t.setDepartment(new Department(tid, null));
			rep.save(t);
			return "添加成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "添加失败";
		}
	}

	@Override
	public String updateTeacher(Teacher t, Integer tid) {
		try {
			t.setDepartment(new Department(tid, null));
			rep.save(t);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
	}

	@Override
	public String deleteTeacher(Integer tid) {
		try {
			rep.deleteById(tid);
			return "删除成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "删除失败";
		}
	}

}
